<template>
  <div class="app-container">
    <h3>分类管理</h3>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-select
            v-model="queryParams.categoryName"
            placeholder="请选择分类名称"
            clearable
            filterable
            @change="handleQuery"
        >
          <el-option
              v-for="item in categoryNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类层级" prop="level">
        <el-select
            v-model="queryParams.level"
            placeholder="请选择分类层级"
            clearable
            filterable
            @change="handleQuery"
        >
          <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:categorys:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:categorys:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:categorys:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:categorys:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categorysList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类ID" align="center" prop="categoryId" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="父分类ID" align="center" prop="parentId" />
      <el-table-column label="分类层级" align="center" prop="level" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
              :type="scope.row.status === '0' ? 'success' : 'danger'"
              effect="light"
          >
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:categorys:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:categorys:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分类管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categorysRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类ID" prop="parentId">
          <el-select
              v-model="form.parentId"
              placeholder="请选择父分类"
              clearable
              filterable
          >
            <el-option
                v-for="item in parentCategoryOptions"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类层级" prop="level">
          <el-select
              v-model="form.level"
              placeholder="请选择分类层级"
              clearable
          >
            <el-option
                v-for="item in levelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-divider content-position="center">商品管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMallProduct">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteMallProduct">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="mallProductList" :row-class-name="rowMallProductIndex" @selection-change="handleMallProductSelectionChange" ref="mallProduct">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品名称" prop="productName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="原价" prop="originalPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.originalPrice" placeholder="请输入原价" />
            </template>
          </el-table-column>
          <el-table-column label="现价" prop="currentPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.currentPrice" placeholder="请输入现价" />
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.stock" placeholder="请输入库存" />
            </template>
          </el-table-column>
          <el-table-column label="销量" prop="sales" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.sales" placeholder="请输入销量" />
            </template>
          </el-table-column>
          <el-table-column label="标签" prop="tags" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.tags" placeholder="请输入标签" />
            </template>
          </el-table-column>
          <el-table-column label="是否热销: 1-是, 0-否" prop="isHot" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.isHot" placeholder="请输入是否热销: 1-是, 0-否" />
            </template>
          </el-table-column>
          <el-table-column label="是否新品: 1-是, 0-否" prop="isNew" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.isNew" placeholder="请输入是否新品: 1-是, 0-否" />
            </template>
          </el-table-column>
          <el-table-column label="是否秒杀: 1-是, 0-否" prop="isSeckill" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.isSeckill" placeholder="请输入是否秒杀: 1-是, 0-否" />
            </template>
          </el-table-column>
          <el-table-column label="秒杀价" prop="seckillPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.seckillPrice" placeholder="请输入秒杀价" />
            </template>
          </el-table-column>
          <el-table-column label="秒杀库存" prop="seckillStock" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.seckillStock" placeholder="请输入秒杀库存" />
            </template>
          </el-table-column>
          <el-table-column label="秒杀开始时间" prop="seckillStartTime" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.seckillStartTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择秒杀开始时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="秒杀结束时间" prop="seckillEndTime" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.seckillEndTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择秒杀结束时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="状态: 0-上架, 1-下架" prop="status" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态: 0-上架, 1-下架">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Categorys">
import { listCategorys, getCategorys, delCategorys, addCategorys, updateCategorys } from "@/api/system/categorys"


const { proxy } = getCurrentInstance()

const categorysList = ref([])
const mallProductList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedMallProduct = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 下拉框选项数据
const categoryNameOptions = ref([])
const levelOptions = ref([
  { label: '一级分类', value: 1 },
  { label: '二级分类', value: 2 },
  { label: '三级分类', value: 3 }
])
const parentCategoryOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryName: null,
    parentId: null,
    level: null,
    sortOrder: null,
    icon: null,
    status: null,
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 获取状态显示文本 */
function getStatusLabel(status) {
  const statusMap = {
    '0': '正常',
    '1': '禁用'
  }
  return statusMap[status] || status
}

/** 查询分类管理列表 */
function getList() {
  loading.value = true
  listCategorys(queryParams.value).then(response => {
    categorysList.value = response.rows
    total.value = response.total
    loading.value = false

    // 更新分类名称下拉框选项
    updateCategoryNameOptions(response.rows)
    // 更新父分类下拉框选项
    updateParentCategoryOptions(response.rows)
  })
}
/** 更新分类名称下拉框选项 */
function updateCategoryNameOptions(data) {
  const uniqueNames = [...new Set(data.map(item => item.categoryName))]
  categoryNameOptions.value = uniqueNames.map(name => ({
    label: name,
    value: name
  }))
}
/** 更新父分类下拉框选项 */
function updateParentCategoryOptions(data) {
  parentCategoryOptions.value = data.filter(item => item.level < 3) // 只显示一级和二级分类作为父分类
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    categoryId: null,
    categoryName: null,
    parentId: null,
    level: null,
    sortOrder: null,
    icon: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  mallProductList.value = []
  proxy.resetForm("categorysRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.categoryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加分类管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _categoryId = row.categoryId || ids.value
  getCategorys(_categoryId).then(response => {
    form.value = response.data
    mallProductList.value = response.data.mallProductList
    open.value = true
    title.value = "修改分类管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categorysRef"].validate(valid => {
    if (valid) {
      form.value.mallProductList = mallProductList.value
      if (form.value.categoryId != null) {
        updateCategorys(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCategorys(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _categoryIds = row.categoryId || ids.value
  proxy.$modal.confirm('是否确认删除分类管理编号为"' + _categoryIds + '"的数据项？').then(function() {
    return delCategorys(_categoryIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 商品管理序号 */
function rowMallProductIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 生成商品编码 */
function generateProductCode() {
  const timestamp = new Date().getTime().toString().slice(-8)
  const random = Math.random().toString(36).substr(2, 6).toUpperCase()
  return `P${timestamp}${random}`
}
/** 商品管理添加按钮操作 */
function handleAddMallProduct() {
  let obj = {}
  obj.productName = ""
  obj.productCode = generateProductCode()
  obj.mainImage = ""
  obj.subImages = ""
  obj.description = ""
  obj.originalPrice = ""
  obj.currentPrice = ""
  obj.stock = ""
  obj.sales = ""
  obj.tags = ""
  obj.isHot = "0"  // 设置默认值
  obj.isNew = "0"  // 设置默认值
  obj.isSeckill = "0"  // 设置默认值
  obj.seckillPrice = ""
  obj.seckillStock = ""
  obj.seckillStartTime = ""
  obj.seckillEndTime = ""
  obj.status = "0"
  mallProductList.value.push(obj)
}

/** 商品管理删除按钮操作 */
function handleDeleteMallProduct() {
  if (checkedMallProduct.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的商品管理数据")
  } else {
    const mallProducts = mallProductList.value
    const checkedMallProducts = checkedMallProduct.value
    mallProductList.value = mallProducts.filter(function(item) {
      return checkedMallProducts.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleMallProductSelectionChange(selection) {
  checkedMallProduct.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/categorys/export', {
    ...queryParams.value
  }, `categorys_${new Date().getTime()}.xlsx`)
}

getList()
</script>
